<template>
  <div class="dashboard-container">

    <div class="filter-container">
      <el-input
        ref="qcode"
        v-model="waybill_no"
        size="medium"
        placeholder="请输入扫描运单号"
        prefix-icon="el-icon-search"
        style="margin-right:10px"
        autofocus
        @keypress.enter.native="submit()"
      />
      <el-button v-if="value == 0" type="primary" size="medium" @click="submit()">
        打 印（ENTER）
      </el-button>
    </div>
    <div style="padding:0 20px 10px">
      <el-card shadow="never">
        <el-row type="flex" class="row-bg">
          <div class="card-content">
            <div class="card-item">
              <el-switch v-model="value" active-text="是否换单" active-color="#1890ff" :active-value="1" />
            </div>
            <div v-if="value == 1" class="card-item">
              <span style="margin-right:10px;font-size:13px">换单公司:</span>
              <el-select v-model="company_code" clearable placeholder="请选择">
                <el-option
                  v-for="item in CompayList"
                  :key="item.company_code"
                  :label="item.company_name"
                  :value="item.company_code"
                />
              </el-select>
            </div>
            <div class="card-item">
              <span style="margin-right:10px;font-size:13px">选择打印机:</span>
              <el-select v-model="printerName" placeholder="请选择打印机" style="width: 420px">
                <el-option v-for="item in printerList" :key="item.name" :label="item.name" :value="item.name" />
              </el-select>
            </div>
            <div v-if="value == 1" type="flex" class="row-bg" justify="end">
              <el-button type="primary" @click="submit()">
                换单并打印
              </el-button>
            </div>
          </div>
        </el-row>

      </el-card>
    </div>

    <div style="padding:0 20px">
      <div class="search">
        <el-input
          v-model="listQuery.waybill_no_origin"
          placeholder="原单号"
          class="input-with-select"
          @keypress.enter.native="reloadList"
        />
        <el-input
          v-model="listQuery.waybill_no"
          placeholder="新单号"
          class="input-with-select"
          @keypress.enter.native="reloadList"
        />
        <el-input
          v-model="listQuery.tid"
          placeholder="系统单号"
          class="input-with-select"
          @keypress.enter.native="reloadList"
        />
        <el-select
          v-model="listQuery.create_uid"
          placeholder="操作人"
          clearable
          @change="reloadList"
        >
          <el-option
            v-for="(item,index) in userlist"
            :key="index"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
        <el-date-picker
          v-model="listQuery.created"
          style="width: 300px;margin:0 10px"
          type="datetimerange"
          range-separator="~"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        />
        <el-button
          size="mini"
          type="primary"
          class="filter-item"
          @click="reloadList"
        >
          查 询
        </el-button>
        <download-excel
          style="margin-left:10px;"
          class="export-excel-wrapper"
          :fetch="importPackageList"
          :fields="json_fields"
          type="xls"
          worksheet="My Worksheet"
          name="换单导出"
          :before-generate="startDownload"
          :before-finish="finishDownload"
        >
          <el-button type="primary" size="mini">导出</el-button>
        </download-excel>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        height="calc(100vh - 330px)"
        style="width: 100%;"
        size="mini"
        border
        tooltip-effect="dark"
        :header-cell-style="{ background: '#eaf1fd', color: '#333' }"
      >
        <el-table-column label="原单号" prop="waybill_no_origin" width="160" />
        <el-table-column label="新单号" prop="waybill_no" width="160" />
        <el-table-column label="系统单号" prop="tid" width="160" />

        <el-table-column label="收件人" prop="order.receiver.name" width="120" />
        <el-table-column label="电话" width="160">
          <template slot-scope="{ row }">
            <span v-if="row.order && row.order.receiver">+{{ row.order.receiver.area_code }} {{ row.order.receiver.mobile
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收件地址" min-width="400">
          <template slot-scope="{ row }">
            <span v-if="row.order && row.order.receiver">{{ row.order.receiver.nation }}{{ row.order.receiver.province
            }}{{ row.order.receiver.city }}{{ row.order.receiver.district }}{{ row.order.receiver.detailed }}</span>
          </template>
        </el-table-column>
        <el-table-column label="取号状态" width="80">
          <template slot-scope="{ row }">
            <span v-if="row.status==0">--</span>
            <span v-if="row.status==1">成功</span>
            <span v-if="row.status==2" style="color:red">失败</span>
          </template>
        </el-table-column>
        <el-table-column label="异常原因" min-width="250">
          <template slot-scope="{ row }">
            <span v-if="row.status==2">{{
              row.waybill_data }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作人" prop="admin.username" width="180" />

        <el-table-column label="换单时间" prop="created" width="180" />

        <!-- <el-table-column
          label="操作"
          align="right"
          width="180"
          class-name="small-padding fixed-width"
          fixed="right"
        >
          <template slot-scope="{ row }">
            <el-button
              v-if="row.is_cancel ==0"
              type="danger"
              @click="delet(row)"
            >
              废弃
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <!-- <Detial :detial="detial" :status="status" :visible="visible" @update="closeDraw" @reload="reloadList" /> -->

    <el-dialog
      title="重复打印检测"
      :visible.sync="cheackRes"
      width="500px"
      :before-close="handleClose"
    >
      <div style="padding:20px">
        <div style="font-size: 16px; margin-top: 15px;">
          以下主运单号重复打印，请确认继续打印
        </div>
        <div v-if="errorData.length > 0" style="font-size: 16px; margin-top: 15px;">
          <el-alert
            v-for="(item,index) in errorData"
            :key="index"
            :title="item"
            :closable="false"
            style="margin-top: 10px;"
            type="error"
            show-icon
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cheackRes = false;">取 消</el-button>
        <el-button type="primary" @click="goOnPrint()">继续打印</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listChange, getChangeWaybillNo, expressLabel, printTimes, checkExpress, getIsStop } from '@/api/order/index'
import { listCourierNo } from '@/api/base/express'

import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// import Detial from './components/flightDetial.vue'
import { doConnect, doPrintHandover } from '@/utils/print'
import { listAdmin } from '@/api/admin/index'
import _ from 'lodash'

export default {
  name: 'Dashboard',
  components: {
    Pagination
    // Detial
  },
  data() {
    return {
      cheackRes: false,
      errorData: [],
      // 实例化一个音频播放器对象
      audio: new Audio(),
      successUrl: require('../../assets/success.wav'),
      printSuccessUrl: require('../../assets/printsuccess.mp3'),
      printErrorUrl: require('../../assets/y1841.wav'),
      userlist: [],
      waybill_no: '',
      data_arr: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        line: '',
        batch_no: '',
        create_uid: '',
        created: []
      },
      visible: false,
      status: 1,
      id: '',
      detial: {},
      message: '',
      CompayList: [],
      value: 0,
      company_code: '',
      printerList: [],
      printLoading: null,
      back: {},
      dialogPrinters: false,
      printerName: '', // 选择的打印机名称
      json_fields: {
        原单号: {
          field: 'waybill_no_origin',
          callback: value => {
            return '&nbsp;' + value
          }
        },
        新单号: {
          field: 'waybill_no',
          callback: value => {
            return '&nbsp;' + value
          }
        },
        系统单号: {
          field: 'tid',
          callback: value => {
            return '&nbsp;' + value
          }
        },
        收件人: 'order.receiver.name',
        电话: 'mobile',
        地址: 'address',
        取号状态: {
          field: 'status',
          // 自定义回调函数
          callback: value => {
            if (value === 0) return '--'
            if (value === 1) return '成功'
            if (value === 2) return '失败'
          }
        },
        异常原因: 'error_data',
        操作人: {
          field: 'admin.username',
          callback: value => {
            return '&nbsp;' + value
          }
        },
        换单时间: 'created'
      }
    }
  },
  computed: {
  },
  watch: {
    back(val) {
      // 打印回调
      printTimes({ document_id: val.printStatus[0].documentID }).then(res => {

      })
      this.printLoading.close()
    }
  },
  mounted() {
    var that = this
    const socket = doConnect()
    socket.onmessage = function(event) {
      console.log(JSON.parse(event.data))
      const res = JSON.parse(event.data)
      if (res.cmd === 'getPrinters') {
        that.printerName = res.defaultPrinter // 默认打印机
        that.printerList = res.printers
      }
      if (res.cmd === 'print') {
        that.printLoading = that.$loading({
          lock: true,
          text: '打印中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      }
      if (res.cmd === 'notifyPrintResult' && res.taskStatus === 'printed') {
        that.back = res
      }
    }
  },
  created() {
    this.getList()
    this.getCompayList()
    this.getUserList()
  },
  methods: {
    // 是否被拦截检测
    cheackInterceot(waybill_no) {
      return new Promise((resolve, reject) => {
        getIsStop({
          waybill_no: waybill_no
        }).then(res => {
          resolve(res.msg)
        })
      })
    },
    handleClose() {
      this.cheackRes = false
    },
    getUserList() {
      listAdmin({
        limit: 9999,
        status: 1
      }).then((response) => {
        this.userlist = response.data.data
      })
    },
    async submitPrint() {
      const msg = await this.cheackInterceot(this.waybill_no)
      if (msg !== '通过') {
        // 开启自动播放
        this.audio.autoplay = true
        this.audio.src = this.printErrorUrl
        this.$message.error(msg)
        return
      }
      // 换单并打印
      if (this.value === 1) {
        getChangeWaybillNo({
          'waybill_no': this.waybill_no,
          'company_code': this.company_code
        }).then(res => {
          this.$message.success(res.msg)
          // 开启自动播放
          this.audio.autoplay = true
          this.audio.src = this.successUrl
          this.getList()
          this.print(res.data.waybill_no)
        })
      } else {
        this.print()
      }
    },
    checkExpressOrders(waybill_no) {
      return new Promise((resolve, reject) => {
        checkExpress({
          waybill_nos: [waybill_no]
        }).then(res => {
          resolve(res.data.errorData)
        })
      })
    },
    print(waybill_no) {
      expressLabel({
        waybill_no: waybill_no || this.waybill_no,
        type: 2
      }).then(async(res) => {
        this.errorData = await this.checkExpressOrders(res.data.waybillCode)
        if (this.errorData.length) {
          this.cheackRes = true
        } else {
          const arr = []
          // 开启自动播放
          this.audio.autoplay = true
          this.audio.src = this.printSuccessUrl
          arr.push(res.data)
          doPrintHandover(arr, this.printerName)
        }
      })
    },
    async goOnPrint() {
      this.cheackRes = false
      expressLabel({
        waybill_no: this.errorData[0],
        type: 2
      }).then(res => {
        const arr = []
        // 开启自动播放
        this.audio.autoplay = true
        this.audio.src = this.printSuccessUrl
        arr.push(res.data)
        doPrintHandover(arr, this.printerName)
      })
    },
    // 线路列表

    getCompayList() {
      listCourierNo({
      }).then(res => {
        this.CompayList = res.data
      })
    },
    reloadList() {
      this.listQuery.page = 1
      this.visible = false
      this.getList()
    },
    getList() {
      this.listLoading = true
      listChange(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.count
        this.listLoading = false
      })
    },
    submit(e) {
      setTimeout(() => {
        const qcode = this.$refs.qcode
        qcode.select()
      }, 300)
      this.submitPrint() // 提交打印
    },

    // 导出
    getPageSize() {
      return new Promise((resolve, reject) => {
        listChange(this.listQuery).then(response => {
          resolve(response.data.count)
        })
      })
    },
    getExcelList(page) {
      const param = _.cloneDeep(this.listQuery)
      param.page = page
      return new Promise((resolve, reject) => {
        listChange(param).then(response => {
          response.data.list.forEach(item => {
            item.mobile = '+' + _.get(item.order, 'receiver.area_code', '') + ' ' + _.get(item.order, 'receiver.mobile', '')
            item.address = _.get(item.order, 'receiver.nation', '') + _.get(item.order, 'receiver.province', '') + _.get(item.order, 'receiver.city', '') + _.get(item.order, 'receiver.district', '') + _.get(item.order, 'receiver.detailed', '')
            if (!item.waybill_data.waybill_no) {
              item.error_data = item.waybill_data
            } else {
              item.error_data = ''
            }
          })
          resolve(response.data.list)
        })
      })
    },
    async importPackageList() {
      const total = await this.getPageSize()
      const page = Math.ceil(total / this.listQuery.limit)
      var data = []
      for (let i = 1; i <= page; ++i) {
        data = data.concat(await this.getExcelList(i))
      }
      return data
    },
    startDownload() {
      this.loadingExcel = this.$loading({
        lock: true,
        text: '导出表格中，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    finishDownload() {
      this.loadingExcel.close()
    }
  }
}
</script>
<style scoped lang="scss">
.filter-container {
  padding: 20px 20px 10px;
  display: flex;
}

.upload-demo {
  margin: 20px 0 10px;
}

.card-content {
  display: flex;
  align-items: center;

  .card-item {
    margin-right: 40px;
  }
}
.search{
  display: flex;
  margin-bottom: 10px;
  .input-with-select{
    width: 200px;
    margin-right: 10px;
  }
}
</style>
